import axios from "axios";
import { TIMEOUT, BASE_URL } from "./config";
import useMainStore from "../../stores/modules/mainStore";
const mainStore = useMainStore();

// 封装axios
class Request {
    // 构造函数
    constructor(baseURL, timeout = 10000) {
        // 创建axios实例
        this.instance = axios.create({
            baseURL, timeout
        })
        // 当前实例的请求拦截器 控制loading组件的显示与隐藏
        this.instance.interceptors.request.use(
            (config) => { mainStore.isLoading = true; return config },
            (err) => { return err })
        // 当前实例的响应拦截器
        this.instance.interceptors.response.use(
            (res) => { mainStore.isLoading = false; return res },
            err => { mainStore.isLoading = false; return err }
        )
    }
    request(config) {
        return new Promise((resolve, reject) => {
            this.instance.request(config).then(res => {
                resolve(res.data)
            }).catch(err => {
                reject(err)
            })
        })
    }
    get(url, params = {}, data = {}) {
        return this.request({ url, params, data, method: "get" })
    }
    post(url, params = {}, data = {}) {
        return this.request({ url, params, data, method: "post" })
    }
}

export default new Request(BASE_URL, TIMEOUT);